package com.alibaba.user.service.impl;

import com.alibaba.basic.constant.BaseConstants;
import com.alibaba.basic.dto.LoginDto;
import com.alibaba.basic.dto.WeChatDto;
import com.alibaba.basic.exception.BusinessException;
import com.alibaba.basic.jwt.JwtUtils;
import com.alibaba.basic.jwt.RsaUtils;
import com.alibaba.basic.jwt.UserInfo;
import com.alibaba.basic.util.AjaxResult;
import com.alibaba.basic.util.HttpUtil;
import com.alibaba.basic.util.MD5Utils;
import com.alibaba.basic.util.StrUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.system.domain.Menu;
import com.alibaba.system.mapper.MenuMapper;
import com.alibaba.system.mapper.PermissionMapper;
import com.alibaba.user.domain.Logininfo;
import com.alibaba.user.domain.User;
import com.alibaba.user.domain.Wxuser;
import com.alibaba.user.dto.BinderDto;
import com.alibaba.user.mapper.LogininfoMapper;
import com.alibaba.user.mapper.UserMapper;
import com.alibaba.user.mapper.WxuserMapper;
import com.alibaba.user.service.ILogininfoService;
import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.google.common.collect.Maps;
import org.apache.commons.httpclient.HttpClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Resource
    private WxuserMapper wxuserMapper;
    @Resource
    private LogininfoMapper logininfoMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private UserMapper userMapper;
    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private MenuMapper menuMapper;
    @Value("${jwt.rsa.pri}")
    private String jwtRsaPrivate;


    @Override
    public AjaxResult wechatLogin(String code) {



        //1.根据code发送请求获取token和openid
        String url = BaseConstants.WeChatConstants.GET_ACK_URL
                .replace("APPID",BaseConstants.WeChatConstants.APPID)
                .replace("SECRET",BaseConstants.WeChatConstants.SECRET)
                .replace("CODE",code);
        String jsonStr = HttpUtil.httpGet(url);
//        System.out.println(jsonStr);

        //{"access_token":"57_3R0PHzOIKX6brh1TbBZKqwsOCHugjzrJeDZgssoAmsF_UFOq-TSTXE3tmZBUr7VIZ_eP71LhIzOeLeh4gua3vVligjDuBCjRiImEAPSAwqc","openid":"oa9wA01X4TNik8bbXWklIyArUZ5c",}
        //2.将响应的json字符串 转成 json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //3.通过openid去t_wxuser中查询
        Wxuser wxuser = wxuserMapper.findByOpenID(openid);

        if(wxuser!=null && wxuser.getUserId()!=null){ //绑定了
            //4.有 绑定过 - 直接免密登录【获取logininfo对象 登录】
            Logininfo logininfo = logininfoMapper.findByUserId(wxuser.getUserId());
                    //生辰uuid
            String token = UUID.randomUUID().toString();
//            //去掉密码和盐值 - 安全
//            logininfo.setPassword(null);
//            logininfo.setSalt(null);
//            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//
//            Map<String, Object> maps = new HashMap<>();
//            maps.put("token",token);
//            maps.put("logininfo",logininfo);
            HashMap<String, Object> maps = loginSuccessJwtHandler(logininfo);
            return AjaxResult.me().setResultObj(maps);
        }else{
            //5.没有 - 需要跳转页面绑定 - 响应给前端进行跳转
            Map<String, Object> map = new HashMap<>();
            map.put("access_token",access_token);
            map.put("openid",openid);
            return AjaxResult.me().setSuccess(false).setResultObj(map);
        }

        // 6.2.不存在告诉前端用户跳转到账号绑定页面，传递参数到前端，因为我们在下个接口需要使用
//        StringBuffer sbr = new StringBuffer()
//                .append("?accessToken=")
//                .append(accessToken)
//                .append("&openId=")
//                .append(openid);
//        return AjaxResult.me().setSuccess(false).setResultObj(sbr);

    }

    @Override
    public AjaxResult wechatBinder(BinderDto binderDto) {
        String phone = binderDto.getPhone();
        String verifyCode = binderDto.getVerifyCode();
        String accesstoken = binderDto.getAccessToken();
        String openId = binderDto.getOpenId();
        //校验
        //1.校验 - 空置校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("数据不能为空");
        }

        //2.校验 - 验证码是否过期  //code:1215215155
        Object redisCode = redisTemplate.opsForValue().get(BaseConstants.VerifyCodeConstant.BUSINESS_BINDER_PREFIX + phone);
        if(redisCode==null){
            throw new BusinessException("验证码过期");
        }
        //3.校验 - 验证码是否正确
        if(!redisCode.toString().split(":")[0].equalsIgnoreCase(verifyCode.trim())){
            throw new BusinessException("验证码错误");
        }

        System.out.println(accesstoken);
        System.out.println(openId);
        //绑定用户：t_wxUser【user_id】 绑定 t_user
        //4.获取WxUser - 发送第三个请求 - json字符串
        String url = BaseConstants.WeChatConstants.GET_USER_URL
                .replace("ACCESS_TOKEN",accesstoken)
                .replace("OPENID",openId);

        String jsonStr = HttpUtil.httpGet(url);
        Wxuser wxuser = jsonStr2Wxuser(jsonStr); //user_id

        //5.通过phone查询User
        User user = userMapper.findByPhone(phone);
        //5.1.如果没有 - 根据phone创建User对象 - 创建Logininfo对象 - 保存Logininfo对象 - 保存User对象
        if(user == null){
            user = phone2User(phone);
            Logininfo logininfoTmp= user2Logininfo(user);

            logininfoMapper.save(logininfoTmp);
            user.setLogininfoId(logininfoTmp.getId());
            userMapper.save(user);
        }

        //6.将User对象的id设置到WxUser对象中
        wxuser.setUserId(user.getId());
        //7.将WxUser对象添加到数据库
        wxuserMapper.save(wxuser);

        //8.做免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        String token = UUID.randomUUID().toString();

        //去掉密码和盐值 - 安全
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        Map<String, Object> map = new HashMap<>();
//        map.put("token",token);
//        map.put("logininfo",logininfo);
        HashMap<String, Object> map = loginSuccessJwtHandler(logininfo);
//
        return AjaxResult.me().setResultObj(map);
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机的纯数据密码
        String randomPwd = StrUtils.getRandomString(6);
        String md5Pwd = MD5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }

}
